name: Early Access

on:
  push:
    branches: [ main ]

env:
  JAVA_VERSION: '22'
  JAVA_DISTRO: 'adopt'

jobs:
  precheck:
    if: github.repository == 'parttimenerd/hello-ebpf' && startsWith(github.event.head_commit.message, 'Releasing version') != true
    runs-on: ubuntu-latest
    outputs:
      VERSION: ${{ steps.vars.outputs.VERSION }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Cancel previous run
        uses: styfle/cancel-workflow-action@0.12.0
        with:
          access_token: ${{ secrets.GITHUB_TOKEN }}

      - name: Setup Java
        uses: actions/setup-java@v4
        with:
          java-version: ${{ env.JAVA_VERSION }}
          distribution: ${{ env.JAVA_DISTRO }}

      - name: Cache local Maven repository
        uses: actions/cache@v4
        with:
          path: ~/.m2/repository
          key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
          restore-keys: ${{ runner.os }}-maven-

      - name: Version
        id: vars
        shell: bash
        run: |
          VERSION=$(./mvnw help:evaluate -Dexpression=project.version -q -DforceStdout)
          echo "VERSION=$(echo $VERSION)" >> $GITHUB_OUTPUT

  release:
    needs: [ precheck ]
    if: endsWith(${{ needs.precheck.outputs.VERSION }}, '-SNAPSHOT')
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Java
        uses: actions/setup-java@v4
        with:
          java-version: ${{ env.JAVA_VERSION }}
          distribution: ${{ env.JAVA_DISTRO }}
          server-id: ossrh
          server-username: MAVEN_USERNAME
          server-password: MAVEN_PASSWORD

      - name: Cache Maven
        uses: actions/cache@v4
        with:
          path: ~/.m2/repository
          key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
          restore-keys: ${{ runner.os }}-m2

      - run: sudo apt-get update && sudo apt-get install -y --no-install-recommends clang libbpf-dev linux-tools-common linux-tools-$(uname -r) gcc-multilib

      - name: Build
        run: ./mvnw -Ppublication -ntp -B --file pom.xml verify

      - name: Deploy
        run: |
          mkdir -p ~/.m2
          echo $SETTINGS_FILE > ~/.m2/settings.xml
          mvn -ntp -B clean source:jar deploy
        env:
          MAVEN_USERNAME: ${{ secrets.JRELEASER_NEXUS2_USERNAME }}
          MAVEN_PASSWORD: ${{ secrets.JRELEASER_NEXUS2_PASSWORD }}
          SIGN_KEY_PASS: ${{ secrets.JRELEASER_GPG_PASSPHRASE }}
          SIGN_KEY: ${{ secrets.JRELEASER_GPG_SECRET_KEY }}
          GPG_PUBLIC_KEY: ${{ secrets.JRELEASER_GPG_PUBLIC_KEY }}
          SIGN_KEY_ID: ${{ secrets.GPG_KEY_NAME }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          SETTINGS_FILE: ${{ secrets.SETTINGS_FILE }}